import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:oramemo/common/styles/colors.dart';
import 'package:oramemo/common/utils/extension_util.dart';
import 'package:oramemo/pages/circle/circle_router.dart';
import 'package:oramemo/widget/my_button.dart';

import 'members_logic.dart';

class DeviceCircleMembersPage extends StatefulWidget {
  const DeviceCircleMembersPage({Key? key}) : super(key: key);

  @override
  State<DeviceCircleMembersPage> createState() =>
      _DeviceCircleMembersPageState();
}

class _DeviceCircleMembersPageState extends State<DeviceCircleMembersPage> {
  // 当前选中的成员索引，用于删除操作
  int? selectedMemberIndex;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MembersLogic>(
        init: MembersLogic(),
        builder: (logic) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // 标题
              Padding(
                padding: EdgeInsets.only(top: 26.h, bottom: 19.h),
                child: Text(
                  '邀请成员，分享与创造',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ),

              // 角色说明
              SizedBox(
                height: 100.h,
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: ListView(
                    scrollDirection: Axis.horizontal,
                    children: [
                      // 邀请按钮
                      _buildMemberAvatar(
                          header: Icon(
                            Icons.add,
                            size: 40.sp,
                            color: Colors.blue,
                          ),
                          name: '邀请',
                          isSelected: true,
                          onTap: () {
                            if (logic.delPermission) {
                              Get.toNamed(CircleRouter.invitationPage);
                            } else {
                              Toast.show('不是管理员，不能邀请成员');
                            }
                          }),

                      // 成员头像
                      ...List.generate(
                        logic.list.length,
                        (index) => _buildMemberAvatar(
                          header: ClipRRect(
                            borderRadius: BorderRadius.circular(12.r),
                            child: Image.network(
                              width: 48.w,
                              height: 48.h,
                              logic.list[index].avatar.toFullUrl(),
                              fit: BoxFit.cover,
                            ),
                          ),
                          name: logic.list[index].nickName ?? '',
                          isSelected: selectedMemberIndex == index,
                          onTap: () {
                            setState(() {
                              if (selectedMemberIndex == index) {
                                selectedMemberIndex = null;
                              } else {
                                selectedMemberIndex = index;
                              }
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 管理员说明
                  Row(
                    children: [
                      if (logic.delPermission)
                        Container(
                          alignment: Alignment.centerRight,
                          width: 58.w,
                          child: Padding(
                            padding: EdgeInsets.only(right: 2.w),
                            child: Icon(
                              AntdIcon.check,
                              color: Colors.black,
                              size: 22.sp,
                            ),
                          ),
                        )
                      else
                         SizedBox(width: 58.w),
                      Text(
                        '管理员',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colours.text,
                        ),
                      ),
                      Text(
                        '（有邀请成员，编辑，删除等管理权限）',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colours.text_gray,
                        ),
                      ),
                    ],
                  ),

                  SizedBox(height: 16.h),

                  // 成员说明
                  Row(
                    children: [

                      if (logic.delPermission)
                        SizedBox(width: 58.w,)
                      else
                      Container(
                        alignment: Alignment.centerRight,
                        width: 58.w,
                        child: Padding(
                          padding: EdgeInsets.only(right: 2.w),
                          child:Icon(
                                  AntdIcon.check,
                                  color: Colors.black,
                                  size: 22.sp,
                                ),
                        ),
                      ),
                      Text(
                        '成员',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colours.text,
                        ),
                      ),
                      Text(
                        '（可评论，编辑，分享）',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colours.text_gray,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              SizedBox(height: 39.h),
              // 删除成员按钮
              if (selectedMemberIndex != null)
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 30.w),
                  child: SizedBox(
                    width: double.infinity,
                    height: 50.h,
                    child: ElevatedButton(
                      onPressed: !logic.delPermission
                          ? null
                          : () {
                              _showDeleteConfirmation();
                            },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF666666),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                      ),
                      child: Text(
                        '删除成员',
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ),
              Spacer(),
            ],
          );
        });
  }

  // 成员头像
  Widget _buildMemberAvatar({
    required Widget header,
    required String name,
    required bool isSelected,
    required VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 15.w),
        child: Column(
          children: [
            Container(
              width: 50.w,
              height: 50.w,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.r),
                border: Border.all(
                  color: isSelected ? Colors.blue : Colors.transparent,
                  width: 1,
                ),
              ),
              child: Center(
                child: header,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              name,
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black87,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 显示删除确认对话框
  void _showDeleteConfirmation() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('确认删除'),
          content: Text('确定要删除该成员吗？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                // 执行删除操作
                if (selectedMemberIndex != null) {
                  setState(() {
                    MembersLogic logic = Get.find();
                    logic.delete(selectedMemberIndex!);
                    selectedMemberIndex = null;
                  });
                }
                Navigator.pop(context);
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }
}
